/*
 * @lc app=leetcode.cn id=1382 lang=javascript
 *
 * [1382] 将二叉搜索树变平衡
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */

var getNodes = function(root, nodes) {
  if(!root) return;
  getNodes(root.left, nodes);
  nodes.push(root);
  getNodes(root.right, nodes);
}
var buildTree = function(nodes, l, r){
  if(l > r) return null;
  const mid = (l + r) >> 1;
  const root = nodes[mid];
  root.left = buildTree(nodes, l, mid - 1);
  root.right  = buildTree(nodes, mid + 1, r);
  return root;
}
var balanceBST = function(root) {
  if(!root) return root;
  let nodes = [];
  getNodes(root, nodes);
  return buildTree(nodes, 0, nodes.length -1);
};
// @lc code=end

